package com.oocl.training.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 统计
 * @author GANAB
 *
 */
public class StatisticUtil {
	private static final String LETTER_REX = "[a-zA-Z]";
	private static final String NUMBER_REX = "\\d";
	private static final String CHINESE_CHAR_REX= "[\u4e00-\u9fa5]";
	private static final String PUNCTUATION_REX= "\\pP|\\pS";
	
	/**
	 * 统计各个字符的数据
	 * @return
	 * @throws IOException 
	 */
	public static Map<String, Integer> analyse(InputStream is) throws IOException{
		Map<String, Integer> resultMap = new HashMap<String, Integer>();
		int letterCount = 0, numberCount = 0, chineseCount = 0, punctuationCount = 0;
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String str="";
		//声明Pattern
		Pattern patternForLetter =  Pattern.compile(LETTER_REX);		
		Pattern patternForNumber = Pattern.compile(NUMBER_REX);
		Pattern patternForChinese = Pattern.compile(CHINESE_CHAR_REX);
		Pattern patternForPunctuation = Pattern.compile(PUNCTUATION_REX);
		//声明Matcher
		Matcher matcherForLetter = null, matcherForNumber = null, matcherForChinese = null, matcherForPunctuation = null;
		while((str=br.readLine())!=null){
			//统计字母
			matcherForLetter = patternForLetter.matcher(str);
			while(matcherForLetter.find()){
				letterCount++;
			}
			//统计数字
			matcherForNumber = patternForNumber.matcher(str);
			while(matcherForNumber.find()){
				numberCount++;
			}
			//统计汉字
			matcherForChinese = patternForChinese.matcher(str);
			while(matcherForChinese.find()){
				chineseCount++;
			}
			//统计字符
			matcherForPunctuation = patternForPunctuation.matcher(str);
			while(matcherForPunctuation.find()){
				punctuationCount++;
			}
			
			//返回值赋值
			resultMap.put("letter", letterCount);
			resultMap.put("number", numberCount);
			resultMap.put("chinese", chineseCount);
			resultMap.put("punctuation", punctuationCount);
		}
		
		return resultMap;
	}
	
}
